<template>
  <el-page-header @back="goBack" style="margin: 20px 50px">
    <template #title>
      <div class="flex items-center">
        <span class="text-large font-600 mr-3"> 购物车 </span>
        <el-tag>请核实好您的购买清单后进行结算</el-tag>
      </div>
    </template>
    <template #content>
      <div class="flex items-center">
        <el-select v-model="selectedAddress" placeholder="选择地址">
          <el-option
            v-for="address in addressData"
            :key="address.id"
            :label="address.label"
            :value="
              address.street +
              address.detail +
              ' ' +
              address.recipient +
              ' ' +
              address.rePhone
            "
          ></el-option>
        </el-select>
      </div>
    </template>
    <template #extra>
      <div class="flex items-center">
        <el-button type="info" disabled>总计金额: {{ totalPrice }}</el-button>
        <el-button type="primary" class="ml-2" @click="checkout"
          >结算</el-button
        >
      </div>
    </template>
  </el-page-header>
  <el-container style="margin: 0 50px">
    <el-main style="display: flex; flex-direction: row; flex-wrap: wrap">
      <div
        class="cart-card-group"
        v-for="(item, index) in cartItems"
        :key="index"
      >
        <el-card class="cart-card">
          <div class="cart-card-image">
            <img
              :src="item.dishesPic"
              alt="商品图片"
              style="width: 100%; height: 300px; object-fit: cover"
            />
          </div>
          <div class="cart-card-info">
            <h3>{{ item.dishesName }}</h3>
            <p>
              <span>价格：</span><span>{{ item.dishesPrice }}</span>
            </p>
            <p>
              <span
                >数量：
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="10"
                  @change="handleChange(item.id, item.quantity)"
                />
              </span>
            </p>
          </div>
          <div class="cart-card-actions">
            <el-button type="danger" @click="removeFromCart(item.id)"
              >移除</el-button
            >
          </div>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { reactive, toRefs, ref, computed } from 'vue'
import {
  getCartApi,
  addNumApi,
  delCartApi,
  clearCartApi
} from '@/api/shopping-cart'
import { buyApi } from '@/api/order'
import { getAdrApi } from '@/api/address'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

export default {
  components: {},
  setup() {
    const data = reactive({
      cartItems: [],
      addressData: [],
      selectedAddress: ''
    })

    const route = useRoute()
    const router = useRouter()
    const totalPrice = computed(() => {
      const total = data.cartItems.reduce(
        (total, item) => total + item.dishesPrice * item.quantity,
        0
      )
      return total.toFixed(2)
    })

    const Addressfind = () => {
      getAdrApi({ userId: store.state.uInfo.userInfo.userId }).then((res) => {
        if (res) {
          data.addressData = res.data
        }
      })
    }

    const store = useStore()

    const cartListGet = () => {
      getCartApi({ userId: store.state.uInfo.userInfo.userId,shopId:route.params.id }).then((res) => {
        data.cartItems = res.data
      })
    }

    const removeFromCart = (itemId) => {
      delCartApi({
        id: itemId
      }).then((res) => {
        if (res) {
          cartListGet()
        }
      })
    }
    
    const handleChange = (productId, value) => {
      addNumApi({id: productId,newQuantity: value}).then((res) => {
        if (res) {
          const updatedCartItems = data.cartItems.map((item) => {
            if (item.productId === productId) {
              return { ...item, quantity: value }
            } else {
              return item
            }
          })
          data.cartItems = updatedCartItems
        }
      })
    }
    const goBack = () => {
      window.history.back()
    }

    const checkout = () => {
      if (data.cartItems.length == 0 || data.selectedAddress == '') {
        ElMessage({
          message: '没有数据或未选择收货地址',
          type: 'error',
          duration: 2000
        })
      } else {
        const submissionObject = {
          userId: store.state.uInfo.userInfo.userId,
          totalPrice: parseFloat(totalPrice.value),
          status: '待处理',
          address: data.selectedAddress,
          shopId:route.params.id,
          detail: data.cartItems
            .map((item) => `${item.dishesName}*${item.quantity}`)
            .join(', ')
        }
        buyApi(submissionObject).then((res) => {
          if (res) {
            clearCart()
          }
        })
      }
    }
    const clearCart = () =>{
      clearCartApi({userId:store.state.uInfo.userInfo.userId,shopId:route.params.id}).then((res)=>{
        if(res){
          cartListGet()
          ElMessage({
            message: '下单成功,请前往订单页面查看',
            type: 'success',
            duration: 2000
          })
          router.push({
            name: 'OrderList'
          })
        }
      })
    }
    Addressfind()
    cartListGet()
    return {
      ...toRefs(data),
      goBack,
      totalPrice,
      checkout,
      removeFromCart,
      handleChange
    }
  },

  methods: {}
}
</script>
<style scoped>
.cart-card-group {
  flex: 0 0 calc(33.33% - 10px); /* 减少10px作为卡片之间的缝隙 */

  max-width: calc(33.33% - 10px); /* 减少10px作为卡片之间的缝隙 */

  margin-right: 10px; /* 增加卡片右边的缝隙 */

  margin-bottom: 10px;
}

/* 最后一个卡片不需要右边的缝隙 */

.cart-card-group:last-child {
  margin-right: 0;
}
</style>
